import { Card, Divider, Button, Form, Input, message } from 'antd'
import styles from './index.module.scss'
import { getUserInfo, login } from '@/api/user'
import { useDispatch } from 'react-redux'
import { setUserInfo } from '@/store/modules/user'
import { useNavigate, useLocation } from 'react-router-dom'

export default function Login () {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const location = useLocation()

  const onFinish = async (values: any) => {
    const res = await login(values)

    if (res.code === 200) {
      // 1、把token存储到仓库中
      dispatch(setUserInfo(res.data))

      // 2、发请求，获取用户信息，然后存储到仓库中
      const res2 = await getUserInfo()
      dispatch(setUserInfo({ ...res.data, ...res2.data }))

      // 3、提示，路由跳转
      message.success(res.message, 1, () => {
        if (location.search) {
          const searchParams = new URLSearchParams(location.search)
          navigate(searchParams.get('redirect') ?? '/')
        } else {
          navigate('/')
        }
      })
    } else {
      message.error(res.message, 0.8)
    }
  }

  type FieldType = {
    adminname?: string
    password?: string
  }

  return (
    <div className={styles.root}>
      <Card className='box-card'>
        <h3 style={{ textAlign: 'center' }}>嗨购商城后台管理系统</h3>
        <Divider />
        <Form
          name='basic'
          style={{ maxWidth: 600 }}
          initialValues={{ adminname: 'admin', password: '123456' }}
          onFinish={onFinish}
          autoComplete='off'
          size='large'
          labelAlign='left'
        >
          <Form.Item<FieldType>
            label='用户名'
            name='adminname'
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            rules={[{ required: true, message: '用户名不能为空' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item<FieldType>
            label='密码'
            name='password'
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            rules={[{ required: true, message: '密码不能为空!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item>
            <Button type='primary' htmlType='submit' block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
